// funds.js
const { runAsync, allAsync, getAsync, retryOperation, log } = require('./dbConfig');

/**
 * 新增经费
 * @param {Object} req - 请求对象，包含经费信息
 * @param {Object} res - 响应对象
 */
const addFunds = async (req, res) => {
  const { funds_date, funds_user_id, funds_user_name, funds_amount, funds_reason, activity_id, activity_name, remarks, create_user } = req.body;
  if (!funds_date || !funds_amount || !funds_reason) {
    return res.status(500).json({ success: false, msg: '日期、金额和原因为必填项', code: '1', data: [] });
  }

  try {
    await retryOperation(() =>
      runAsync(
        `INSERT INTO sk_funds (funds_date, funds_user_id, funds_user_name, funds_amount, funds_reason, activity_id, activity_name, remarks, create_user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [funds_date, funds_user_id, funds_user_name, funds_amount, funds_reason, activity_id, activity_name, remarks, create_user]
      )
    );
    const result = await getAsync(`SELECT last_insert_rowid() as id`);
    const lastID = result.id;
    log(`Inserted ID: ${lastID}`);
    res.json({ success: true, msg: '新增成功', code: '0', data: [lastID] });
  } catch (err) {
    log(`新增经费失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '新增经费信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 修改经费信息
 * @param {Object} req - 请求对象，包含更新信息和 ID
 * @param {Object} res - 响应对象
 */
const updateFunds = async (req, res) => {
  const { id, funds_date, funds_user_id, funds_user_name, funds_amount, funds_reason, activity_id, activity_name, remarks, update_user } = req.body;

  try {
    await retryOperation(() =>
      runAsync(
        `UPDATE sk_funds SET funds_date = ?, funds_user_id = ?, funds_user_name = ?, funds_amount = ?, funds_reason = ?, activity_id = ?, activity_name = ?, remarks = ?, update_user = ?, update_time = CURRENT_TIMESTAMP WHERE id = ? AND del_flag = '0'`,
        [funds_date, funds_user_id, funds_user_name, funds_amount, funds_reason, activity_id, activity_name, remarks, update_user, id]
      )
    );
    res.json({ success: true, msg: '修改成功', code: '0', data: [] });
  } catch (err) {
    log(`修改经费失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '修改经费信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 删除经费（逻辑删除）
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const deleteFunds = async (req, res) => {
  const { id } = req.params;

  try {
    await retryOperation(() =>
      runAsync(`UPDATE sk_funds SET del_flag = '1' WHERE id = ?`, [id])
    );
    res.json({ success: true, msg: '删除成功', code: '0', data: [] });
  } catch (err) {
    log(`删除经费失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '删除经费信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 查询经费列表（带搜索条件和分页）
 * @param {Object} req - 请求对象，包含搜索条件和分页参数
 * @param {Object} res - 响应对象
 */
const getPageFundsList = async (req, res) => {
  const { funds_date, funds_user_id, funds_user_name, activity_id, activity_name, page, size } = req.query;

  const pageNum = parseInt(page) || 1; // 默认第 1 页
  const pageSize = parseInt(size) || 10; // 默认每页 10 条

  let query = 'SELECT * FROM sk_funds WHERE del_flag = \'0\'';
  let countQuery = 'SELECT COUNT(*) as total FROM sk_funds WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (funds_date) {
    query += ' AND funds_date LIKE ?';
    countQuery += ' AND funds_date LIKE ?';
    params.push(`%${funds_date}%`);
    countParams.push(`%${funds_date}%`);
  }

  if (funds_user_id) {
    query += ' AND funds_user_id = ?';
    countQuery += ' AND funds_user_id = ?';
    params.push(funds_user_id);
    countParams.push(funds_user_id);
  }

  if (funds_user_name) {
    query += ' AND funds_user_name LIKE ?';
    countQuery += ' AND funds_user_name LIKE ?';
    params.push(`%${funds_user_name}%`);
    countParams.push(`%${funds_user_name}%`);
  }

  if (activity_id) {
    query += ' AND activity_id = ?';
    countQuery += ' AND activity_id = ?';
    params.push(activity_id);
    countParams.push(activity_id);
  }

  if (activity_name) {
    query += ' AND activity_name LIKE ?';
    countQuery += ' AND activity_name LIKE ?';
    params.push(`%${activity_name}%`);
    countParams.push(`%${activity_name}%`);
  }

  query += ' ORDER BY id DESC LIMIT ? OFFSET ?';
  params.push(pageSize, (pageNum - 1) * pageSize);

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`Get funds list error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

/**
 * 查询经费列表（带搜索条件不分页）
 * @param {Object} req - 请求对象，包含搜索条件
 * @param {Object} res - 响应对象
 */
const getFundsList = async (req, res) => {
  const { funds_date, funds_user_id, funds_user_name, activity_id, activity_name } = req.query;

  let query = 'SELECT * FROM sk_funds WHERE del_flag = \'0\'';
  let countQuery = 'SELECT COUNT(*) as total FROM sk_funds WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (funds_date) {
    query += ' AND funds_date LIKE ?';
    countQuery += ' AND funds_date LIKE ?';
    params.push(`%${funds_date}%`);
    countParams.push(`%${funds_date}%`);
  }

  if (funds_user_id) {
    query += ' AND funds_user_id = ?';
    countQuery += ' AND funds_user_id = ?';
    params.push(funds_user_id);
    countParams.push(funds_user_id);
  }

  if (funds_user_name) {
    query += ' AND funds_user_name LIKE ?';
    countQuery += ' AND funds_user_name LIKE ?';
    params.push(`%${funds_user_name}%`);
    countParams.push(`%${funds_user_name}%`);
  }

  if (activity_id) {
    query += ' AND activity_id = ?';
    countQuery += ' AND activity_id = ?';
    params.push(activity_id);
    countParams.push(activity_id);
  }

  if (activity_name) {
    query += ' AND activity_name LIKE ?';
    countQuery += ' AND activity_name LIKE ?';
    params.push(`%${activity_name}%`);
    countParams.push(`%${activity_name}%`);
  }

  query += ' ORDER BY id DESC';

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`获取经费信息列表失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '获取经费列表失败，请刷新重试', code: '1', data: [] });
  }
};

/**
 * 查询经费详情
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const queryFundsDetail = async (req, res) => {
  const { id } = req.params;

  try {
    const row = await getAsync('SELECT * FROM sk_funds WHERE id = ? AND del_flag = \'0\'', [id]);
    if (!row) {
      return res.status(500).json({ success: false, msg: '未查询到经费信息', code: '1', data: [] });
    }
    res.json({ data: row, code: '0', success: true, msg: '查询详情成功' });
  } catch (err) {
    log(`Get funds detail error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

// 模块导出
module.exports = { addFunds, updateFunds, deleteFunds, getPageFundsList, getFundsList, queryFundsDetail };